<template>
  <view class="feather-icon" v-html="svgIcon"></view>
</template>

<script setup>
import { ref, computed, onMounted, watch } from "vue";
import feather from "feather-icons";

const props = defineProps({
  name: {
    type: String,
    required: true,
  },
  size: {
    type: [Number, String],
    default: 24,
  },
  color: {
    type: String,
    default: "currentColor",
  },
  strokeWidth: {
    type: [Number, String],
    default: 2,
  },
});

const svgIcon = ref("");

// 生成SVG图标
const generateIcon = () => {
  try {
    if (feather.icons[props.name]) {
      // 获取图标
      const icon = feather.icons[props.name];

      // 计算实际尺寸（单位为px）
      const actualSize =
        typeof props.size === "number" ? props.size : parseInt(props.size);

      // 设置图标属性
      icon.attrs.width = actualSize;
      icon.attrs.height = actualSize;
      icon.attrs.stroke = props.color;
      icon.attrs["stroke-width"] = props.strokeWidth;

      // 获取SVG图标
      svgIcon.value = icon.toSvg();
    } else {
      console.error(`Icon "${props.name}" not found in Feather Icons`);
    }
  } catch (error) {
    console.error("Error loading Feather icon:", error);
  }
};

// 监听属性变化
watch(
  () => [props.name, props.size, props.color, props.strokeWidth],
  () => {
    generateIcon();
  }
);

// 组件挂载时生成图标
onMounted(() => {
  generateIcon();
});
</script>

<style>
.feather-icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
}

.feather-icon svg {
  min-width: 1em;
  min-height: 1em;
}
</style>
